package com.ware.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.enums.PurchaseDetailStatusEnum;
import com.common.enums.PurchaseStatusEnum;
import com.common.utils.PageUtils;
import com.common.utils.Query;
import com.ware.dao.PurchaseDao;
import com.ware.entity.PurchaseDetailEntity;
import com.ware.entity.PurchaseEntity;
import com.ware.service.PurchaseDetailService;
import com.ware.service.PurchaseService;
import com.ware.service.WareSkuService;
import com.ware.vo.MergeVo;
import com.ware.vo.PurchaseDoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailService purchaseDetailService;

    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryUnreceivePage(Map<String, Object> params) {
        LambdaQueryWrapper<PurchaseEntity> queryWrapper = new LambdaQueryWrapper<>();
        String key = (String) params.get("key");
        String status = (String) params.get("status");
        String wareId = (String) params.get("wareId");
//        if (StringUtils.hasText(key)) {
//            queryWrapper.and(w -> {
//                w.eq("purchase_id", key).or().eq("sku_id", key);
//            });
//        }

        queryWrapper.eq(StringUtils.hasText(status), PurchaseEntity::getStatus, status);
        queryWrapper.eq(StringUtils.hasText(wareId), PurchaseEntity::getWareId, wareId);
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                queryWrapper
        );
        return new PageUtils(page);
    }

    @Override
    public void received(List<Long> ids) {
        //1.确认当前采购单状态
        List<PurchaseEntity> collect = ids.stream()
                .map(this::getById)
                .filter(id -> id.getStatus() == PurchaseStatusEnum.CREATED.getCode() ||
                        id.getStatus() == PurchaseStatusEnum.ASSIGNED.getCode())
                .peek(item -> {
                    item.setStatus(PurchaseStatusEnum.RECEIVE.getCode());
                    item.setUpdateTime(new Date());
                }).collect(Collectors.toList());
        //2.改变采购单状态
        this.updateBatchById(collect);
        //3.改变采购项目状态
        if (CollectionUtils.isNotEmpty(collect)) {
            collect.forEach(item -> {
                List<PurchaseDetailEntity> entities = purchaseDetailService.listDetailByPurchaseId(item.getId());
                List<PurchaseDetailEntity> detailEntities = entities.stream().map(entity -> {
                    PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                    purchaseDetailEntity.setId(entity.getId());
                    purchaseDetailEntity.setStatus(PurchaseDetailStatusEnum.BUYING.getCode());
                    return purchaseDetailEntity;
                }).collect(Collectors.toList());
                purchaseDetailService.updateBatchById(detailEntities);
            });
        }
    }

    @Override
    public void done(PurchaseDoneVo doneVo) {
        //1.改变采购项状态
        AtomicBoolean flag = new AtomicBoolean(true);
        List<PurchaseDetailEntity> updates = new ArrayList<>();
        doneVo.getItems().forEach(item -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            if (item.getStatus() == PurchaseDetailStatusEnum.HASERROR.getCode()) {
                flag.set(false);
                purchaseDetailEntity.setStatus(item.getStatus());
            } else {
                //2.将成功采购的进行入库
                purchaseDetailEntity.setStatus(PurchaseDetailStatusEnum.FINISH.getCode());
                PurchaseDetailEntity entity = purchaseDetailService.getById(item.getItemId());
                wareSkuService.addStock(entity.getSkuId(), entity.getWareId(), entity.getSkuNum());
            }
            purchaseDetailEntity.setId(item.getItemId());
            updates.add(purchaseDetailEntity);
        });
        purchaseDetailService.updateBatchById(updates);
        //3.改变采购单状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(doneVo.getId());
        purchaseEntity.setStatus(flag.get() ? PurchaseStatusEnum.FINISH.getCode() :
                PurchaseStatusEnum.HASERROR.getCode());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean mergePurchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        List<Long> items = mergeVo.getItems();
        Long finalPurchaseId = purchaseId;
        List<Long> collect = items.stream()
                .filter(i -> {
                            PurchaseDetailEntity purchaseDetailEntity = purchaseDetailService.getById(i);
                            return purchaseDetailEntity.getStatus() == PurchaseDetailStatusEnum.CREATED.getCode()
                                    || purchaseDetailEntity.getStatus() == PurchaseDetailStatusEnum.ASSIGNED.getCode();
                        }
                ).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(collect)) {
            //新建采购单的情况
            if (Objects.isNull(purchaseId)) {
                PurchaseEntity purchaseEntity = new PurchaseEntity();
                purchaseEntity.setCreateTime(new Date());
                purchaseEntity.setUpdateTime(new Date());
                purchaseEntity.setStatus(PurchaseStatusEnum.CREATED.getCode());
                this.save(purchaseEntity);
                purchaseId = purchaseEntity.getId();
            }
            List<PurchaseDetailEntity> collect1 = collect.stream()
                    .map(i -> {
                        PurchaseDetailEntity purchaseDetailEntity = purchaseDetailService.getById(i);
                        purchaseDetailEntity.setPurchaseId(finalPurchaseId);
                        purchaseDetailEntity.setId(i);
                        purchaseDetailEntity.setStatus(PurchaseDetailStatusEnum.ASSIGNED.getCode());
                        return purchaseDetailEntity;
                    }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(collect1);
            //优化时间更新
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setId(purchaseId);
            purchaseEntity.setUpdateTime(new Date());
            //领取采购单最终是更新操作
            return this.updateById(purchaseEntity);
        } else {
            return false;
        }
    }

}